package org.groupg.project;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import org.groupg.project.config.JsonProxyConfig;
import org.groupg.project.config.ProxyConfig;
import org.groupg.project.config.RuleConfig;
import org.groupg.project.config.XmlProxyConfig;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExampleConfigGenerator {

    public static void generateExampleConfigs(String outputDir) throws IOException {
        Path dirPath = Paths.get(outputDir);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        ProxyConfig exampleConfig = createExampleConfig();

        // 配置JSON序列化
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);

        // 配置XML序列化
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

        // 生成JSON示例 - 使用自定义JSON结构
        File jsonExample = new File(outputDir, "example-config.json");
        JsonProxyConfig jsonConfig = JsonProxyConfig.fromProxyConfig(exampleConfig);
        jsonMapper.writeValue(jsonExample, jsonConfig);

        // 生成XML示例 - 使用自定义XML结构
        File xmlExample = new File(outputDir, "example-config.xml");
        XmlProxyConfig xmlConfig = XmlProxyConfig.fromProxyConfig(exampleConfig);
        xmlMapper.writeValue(xmlExample, xmlConfig);

        System.out.println("示例文件已经输出到文件夹中: " + outputDir);
        System.out.println(" - " + jsonExample.getAbsolutePath());
        System.out.println(" - " + xmlExample.getAbsolutePath());
    }

    private static ProxyConfig createExampleConfig() {
        ProxyConfig exampleConfig = new ProxyConfig();
        Map<Integer, List<RuleConfig>> portRules = new HashMap<>();

        // 添加示例规则 - 与ConfigLoader期望的格式完全匹配
        portRules.put(8080, Arrays.asList(
                new RuleConfig("api-service", "^/api/.*", "api.example.com", 80, Boolean.FALSE, "$1", 0),
                new RuleConfig("static-assets", "^/static/.*", "static.example.com", 80, Boolean.FALSE, "/resource/$1", 1)
        ));

        portRules.put(8081, Arrays.asList(
                new RuleConfig("admin-console", "^/admin/.*", "admin.example.com", 8080, Boolean.FALSE, "$1", 0),
                new RuleConfig("metrics", "^/metrics", "monitoring.example.com", 9090, Boolean.FALSE, "$1", 0)
        ));

        exampleConfig.setPortRules(portRules);
        return exampleConfig;
    }
}